package cong.cheng.jwt;


import io.jsonwebtoken.*;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class Test01 {

    private static long time = 1000 * 60 * 60 * 24;
    private static String signature = "admin";

    public static void main(String[] args) {


        // 生成一个256位的密钥
        SecureRandom secureRandom = new SecureRandom();
        byte[] keyBytes = new byte[256];
        secureRandom.nextBytes(keyBytes);

        // 将密钥转换为Base64字符串
        String base64Key = Base64.getEncoder().encodeToString(keyBytes);

        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                // Header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                // Payload
                .claim("username", "tom")
                .claim("role", "admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                // Signature
                .signWith(SignatureAlgorithm.HS256, base64Key)
                .compact();

        //输出密钥
        System.out.println(base64Key);
        // 输出生成的JWT令牌
        System.out.println(jwtToken);

        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(base64Key).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        System.out.println(claims.get("username"));
        System.out.println(claims.get("role"));
        System.out.println(claims.getId());
        System.out.printf(claims.getSubject());
    }

}
